package com.wefans.wefansapp.common.tool.popup;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wefans.wefansapp.R;
import com.wefans.wefansapp.common.tool.data.MFDataManager;
import com.wefans.wefansapp.common.tool.data.ResDefaultData;
import com.wefans.wefansapp.common.tool.debug.MFDebug;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager.IOnNetworkListener;
import com.wefans.wefansapp.common.tool.network.model.NetJsonData;
import com.wefans.wefansapp.common.tool.network.model.NetMessage;
import com.wefans.wefansapp.common.tool.network.model.NetUploadMessage;
import com.wefans.wefansapp.common.tool.preference.MFSharedPreference;
import com.wefans.wefansapp.common.tool.utils.MFToastUtil;

public class CameraDialog extends Activity implements OnClickListener{
	private static final int PICK_FROM_CAMERA = 0;
	private static final int PICK_FROM_ALBUM = 1;
	private static final int CROP_FROM_CAMERA = 2;
	
	private Uri mImageCaptureUri;
	private Button mBtnClose = null;
	private Button mBtnDelete = null;
	private Button mBtnCamera = null;
	private Button mBtnAlbum = null;
	
	private MFSharedPreference mPrf = null;
	
//	SettingPreference mPreference;
	
	public static final String STRSAVEPATH = Environment.getExternalStorageDirectory()+"/FandomS/";
	
	@SuppressLint("NewApi")
	protected void onCreate(Bundle savedInstanceState){
		StrictMode.enableDefaults();
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);	
		getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setContentView(R.layout.dialog_camera);
        
        mBtnClose=(Button)findViewById(R.id.BTN_CLOSE);       		
        mBtnClose.setOnClickListener(this);
        
        mBtnCamera=(Button)findViewById(R.id.BTN_CAMERA);
        mBtnCamera.setOnClickListener(this);
        
        mBtnAlbum=(Button)findViewById(R.id.BTN_ALBUM);
        mBtnAlbum.setOnClickListener(this);
        
        mBtnDelete=(Button)findViewById(R.id.BTN_DELETE);
        mBtnDelete.setOnClickListener(this);
        
        mPrf = new MFSharedPreference(this);
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
			case R.id.BTN_CLOSE:{
				finish();
			}
				break;
			case R.id.BTN_CAMERA:{
				doTakePhotoAction();
			}	
				break;
			case R.id.BTN_ALBUM:{
				doTakeAlbumAction();
			}	
				break;
			case R.id.BTN_DELETE:{
				doDeleteAction();
			}
				break;
			
		}		
	}
	
	/**
	 * 카메라에서 이미지 가져오기
	 */
	private void doTakePhotoAction() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		mImageCaptureUri = createSaveCropFile();

		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
		startActivityForResult(intent, PICK_FROM_CAMERA);
	}
	/**
	 * 앨범에서 이미지 가져오기
	 */
	private void doTakeAlbumAction() {
		// 앨범 호출
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
		startActivityForResult(intent, PICK_FROM_ALBUM);
	}	
	
	/**
	 * 앨범에서 이미지 가져오기
	 */
	private void doDeleteAction() {
		File file = new File(STRSAVEPATH);
		String photourl= STRSAVEPATH+"tmp_" + MFDataManager.getInstance(getApplicationContext()).getMebmerIdx() + ".jpg";
		File photofile=new File(photourl);
		if(!file.exists() || !photofile.exists()){
//			file.mkdirs();
			AlertDialog.Builder ab = new AlertDialog.Builder(CameraDialog.this);
			ab.setMessage(R.string.no_image)
					.setIcon(R.drawable.ic_launcher)
					.setTitle(R.string.app_name)
					.setCancelable(false)
					.setPositiveButton(R.string.confirm,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							}).show();
			
		} else{
			requestDeletePhoto();
		}
	}
	
	private Uri createSaveCropFile(){
		Uri uri;
		File file = null;
//		String url = "tmp_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
		String url = "tmp_" + MFDataManager.getInstance(getApplicationContext()).getMebmerIdx() + ".jpg";
		String str = Environment.getExternalStorageState();
		MFDebug.e("str=["+str+"]");
		if(str.equals(Environment.MEDIA_MOUNTED)){
			file = new File(STRSAVEPATH);
			if(!file.exists()){
				file.mkdirs();
			}
		}
		else{
			Toast.makeText(CameraDialog.this, "SD Card 인식 실패", Toast.LENGTH_SHORT).show();
			finish();
		}
		uri = Uri.fromFile(new File(file, url));
		MFDebug.e("uri=["+uri+"]");
//		String uriSt= uri.toString();
//		String photo_path = "file://"+uriSt.substring(8, uriSt.length());
//		MFDebug.e("photo_path=["+photo_path+"]");
//		uri= Uri.parse(photo_path);
		return uri;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case CROP_FROM_CAMERA: {
			// 크롭이 된 이후의 이미지를 넘겨 받습니다.
			// 이미지뷰에 이미지를 보여준다거나 부가적인 작업 이후에
			// 임시 파일을 삭제합니다.
			
			MFDebug.e("CROP_FROM_CAMERA");
			
			String full_path = mImageCaptureUri.getPath();
			String file_name = "tmp_" + MFDataManager.getInstance(getApplicationContext()).getMebmerIdx() + ".jpg";
//			doFileUpload(full_path);
			requestUploadPhoto(full_path, file_name);
			break;
		}
		case PICK_FROM_ALBUM: {
			// 이후의 처리가 카메라와 같으므로 일단 break없이 진행합니다.
			mImageCaptureUri = data.getData();
			MFDebug.e("PICK_FROM_ALBUM mImageCaptureUri=["+mImageCaptureUri+"]");
			File original_file = getImageFile(mImageCaptureUri);
			MFDebug.e("PICK_FROM_ALBUM original_file=["+original_file+"]");
			
			mImageCaptureUri = createSaveCropFile();
			MFDebug.e("PICK_FROM_ALBUM mImageCaptureUri=["+mImageCaptureUri+"]");
			
			File cpoy_file = new File(mImageCaptureUri.getPath());
			MFDebug.e("PICK_FROM_ALBUM cpoy_file=["+cpoy_file+"]");

			// SD카드에 저장된 파일을 이미지 Crop을 위해 복사한다.
			copyFile(original_file , cpoy_file);			
			MFDebug.e("mImageCaptureUri=[" + mImageCaptureUri + "]");
		}
		case PICK_FROM_CAMERA: {
			// 이미지를 가져온 이후의 리사이즈할 이미지 크기를 결정합니다.
			// 이후에 이미지 크롭 어플리케이션을 호출하게 됩니다.

			Intent intent = new Intent("com.android.camera.action.CROP");
			MFDebug.e("mImageCaptureUri=["+mImageCaptureUri+"]");
			intent.setDataAndType(mImageCaptureUri, "image/*");
			MFDebug.e("mImageCaptureUri=[" + mImageCaptureUri + "]");
			
//			 Crop한 이미지를 저장할 Path
			intent.putExtra("output", mImageCaptureUri);
//			intent.putExtra("outputX", 200);
//			intent.putExtra("outputY", 200);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			MFDebug.e("디바이스 체크=["+Build.MODEL+"] device is=["+Build.DEVICE+"] ProductName is=["+Build.PRODUCT+"]");
			if(Build.MODEL.equalsIgnoreCase("Nexus 5"))
			{
				MFDebug.e("");
				intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri.toString());
			}
			else{
				intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
			}
//			intent.putExtra("return-data", true);
			// Return Data를 사용하면 번들 용량 제한으로 크기가 큰 이미지는
			// 넘겨 줄 수 없다.
			MFDebug.e("PICK_FROM_CAMERA");
			startActivityForResult(intent, CROP_FROM_CAMERA);
			MFDebug.e("PICK_FROM_CAMERA2");
			break;
		}
		}
	}	
	
	private void requestUploadPhoto(String strFilePath, String strFileName) {
		
		String strUrl = MFNetworkManager.BASE_URL + "/my/set_profile.php";

		MFNetworkManager netMng = MFNetworkManager.getInstance(getApplicationContext());
		netMng.requestUploadImage(MFNetworkManager.REQUEST_UPLOAD_PHOTO, strUrl, strFilePath, strFileName, mNetworkListener);
		
	}
	
	private File getImageFile(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		if (uri == null) {
			MFDebug.e("uri = null");
			uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		}

		Cursor mCursor = getContentResolver().query(uri, projection, null, null, MediaStore.Images.Media.DATE_MODIFIED + " desc");
		if(mCursor == null || mCursor.getCount() < 1) {
			return null; // no cursor or no record
		}
		int column_index = mCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		MFDebug.e("column_index=["+column_index+"]");
		mCursor.moveToFirst();

		String path = mCursor.getString(column_index);
		MFDebug.e("path=["+path+"]");

		if (mCursor !=null ) {
			mCursor.close();
			mCursor = null;
		}

		return new File(path);
	}
	
	public static boolean copyFile(File srcFile, File destFile) {
		boolean result = false;
		try {
			InputStream in = new FileInputStream(srcFile);
			try {
				result = copyToFile(in, destFile);
			} finally  {
				in.close();
			}
		} catch (IOException e) {
			result = false;
		}
		return result;
	}	
	
	private static boolean copyToFile(InputStream inputStream, File destFile) {
		try {
			OutputStream out = new FileOutputStream(destFile);
			try {
				byte[] buffer = new byte[4096];
				int bytesRead;
				while ((bytesRead = inputStream.read(buffer)) >= 0) {
					out.write(buffer, 0, bytesRead);
				}
			} finally {
				out.close();
			}
			return true;
		} catch (IOException e) {
			return false;
		}
	}
	
	private void requestDeletePhoto() {
		String strUrl = MFNetworkManager.BASE_URL + "/my/set_profile_del.php";

		Hashtable<String, String> body = new Hashtable<String, String>();
		body.put("mem_idx", MFDataManager.getInstance(getApplicationContext()).getMebmerIdx());
		
		MFNetworkManager.getInstance(this).requestPostData(MFNetworkManager.REQUEST_DELETE_PHOTO, strUrl, body, mNetworkListener);
	}

	IOnNetworkListener mNetworkListener = new IOnNetworkListener() {
		
		@Override
		public void onNetMessage(int resultCode, NetMessage message) {
			try {
	            //서버 여동 데이터
				long magicNum = 0;
				String json = "";
				
	            if( message instanceof NetJsonData) {
	                magicNum = ((NetJsonData) message).getMagicNum();
	                json = ((NetJsonData) message).getResponseJson();
	            } else if (message instanceof NetUploadMessage) {
	            	magicNum = ((NetUploadMessage) message).getMagicNum();
	                json = ((NetUploadMessage) message).getResponseJson();
	            } else {
	            	return;
	            }
	            
                if( json == null ) {
                    throw new Exception("invalid json data");
                }
                
                Gson gson = new Gson();
                
                ResDefaultData resultData = (ResDefaultData)gson.fromJson(json, ResDefaultData.class);
                if( resultData == null ) {
                    throw new Exception("Gson parsing error");
                }
                
                if (magicNum == MFNetworkManager.REQUEST_DELETE_PHOTO) {
                	
                    if (resultData.isSuccsess()) {
                    	String photourl= STRSAVEPATH+"tmp_" + MFDataManager.getInstance(getApplicationContext()).getMebmerIdx() + ".jpg";
            			File photofile=new File(photourl);
            			photofile.delete();
            			AlertDialog.Builder ab = new AlertDialog.Builder(CameraDialog.this);
            			ab.setMessage(R.string.delete_complete)
            					.setIcon(R.drawable.ic_launcher)
            					.setTitle(R.string.app_name)
            					.setCancelable(false)
            					.setPositiveButton(R.string.confirm,
            							new DialogInterface.OnClickListener() {
            								public void onClick(DialogInterface dialog,
            										int which) {									
            									Intent intent = new Intent();
            									setResult(RESULT_OK,intent);
            									finish();
            								}
            							}).show();		
                    }
                } else if (magicNum == MFNetworkManager.REQUEST_UPLOAD_PHOTO) {
                	if (resultData.isSuccsess()) {
                		String full_path = mImageCaptureUri.getPath();
                		String photo_path = full_path.substring(4, full_path.length());
            			Intent intent = new Intent();
            			intent.putExtra("photoPATH", full_path);
            			setResult(RESULT_OK,intent);
            			finish();
            			MFDebug.e("full_path=["+full_path+"]");
            			MFDebug.e("photo_path=["+photo_path+"]");
                	} else {
                		MFToastUtil.NetResponseToast(getApplicationContext(), resultData.getResultcode(), resultData.getResultmsg());
                	}
                }
	        } catch(Exception e) {	        	
	            MFDebug.e(e);
	        }		
		}
	};
}

